package dse.messages.multiversion;

import dse.*;
import dse.messages.Message;
import dse.messages.MessageHandler;
import dse.messages.MessageSender;
import dse.messages.MessageType;

public class RequestMaxTSMessageHandler extends MessageSender implements
		MessageHandler {
	private DataObject dobj;
	private VersionReader versionReader;
	
	public RequestMaxTSMessageHandler (
			Experiment experiment,
			DataObject dobj,
			VersionReader versionReader
			)
	{
		super(experiment);
		
		this.dobj = dobj;
		this.versionReader = versionReader;
	}
	
	
	@Override
	public boolean acceptMessage(Message message) {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public void messageInterupted(ExperimentRecorder recorder, Message message,
			double time) {
		// TODO Auto-generated method stub
		recorder.debug(this, "msgIntrpt: " + message, time);
		versionReader.readVersion(recorder, -1, time);
	}

	@Override
	public void messageReceived(ExperimentRecorder recorder, Message message, double time) {
		// TODO Auto-generated method stub
		recorder.debug(this, "msgRcvd: " + message, time);
		if (message.messageType() != MessageType.RequestMaxTS) {
			recorder.warn(
					"RequestMaxTSMessageHandler recieved " + 
					message.messageType() + " message."
					);
			return;
		}			
		DataShare share = message.to().getDataShare(dobj);
		if(share != null){
			int seq = 0;
			if(share.getVersions().size() > 0)
				seq = share.getLatest().getSequence();
			Message m = super.createVersionResponseV3Message(
					message.to(), message.from(), seq, message.purpose(), versionReader);
			recorder.debug(this, "new msg: " + m, time);
			experiment.messageQueue().enqueueMessage(m, time);
		}
		else{
			messageInterupted(recorder, message, time);
		}
	}
}
